/**
 * axios 二次封装
 */

import axios from 'axios'
import config from '../config'
import { ElMessage } from 'element-plus'
import router from '../router'
import ErrorComponent from '../views/ErrorMsg.vue'

const TOKEN_INVALID = 'token错误  重新登录'
const NETWORK_ERROR = '网络异常'
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000
  // headers:
})

//请求拦截
service.interceptors.request.use(req => {
  //todo
  const headers = req.headers
  if (!headers.Authorization) {
    headers.Authorization = 'leeleelee'
  }

  return req
})

//响应拦截
// service.interceptors.response.use(undefined, function (error,res){
//     if (error.response && error.response.status === 500) {
//       // 在这里进行处理
//       console.log('服务器出现错误',res);
//     }
//     return Promise.reject(error);
//   });

service.interceptors.response.use(
  res => {
    const { code, data, msg } = res.data
    // console.log(code, data, msg)
    if (code == 200) {
      return data
    } else if (code === 4000) {
      ElMessage.error(TOKEN_INVALID)
      setTimeout(() => {
        router.push('/login')
      }, 1.5 * 10000)
      return Promise.reject(TOKEN_INVALID)
    } else {
      ElMessage.error(msg || NETWORK_ERROR)

      return Promise.reject(msg || NETWORK_ERROR)
    }
  },
  error => {
    // console.log('拦截器响应失败')
    // console.log(error)
    
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误(400)'
          const tokenEvent = new CustomEvent('errorOccurred', {
            detail: 'token 失效'
          })
          window.dispatchEvent(tokenEvent)
          break
        case 401:
          error.message = '未授权，请重新登录(401)'
          break
        case 403:
          error.message = '拒绝访问(403)'
          break
        case 404:
          error.message = '请求出错(404)'
          break
        case 408:
          error.message = '请求超时(408)'
          break
        case 500:
          error.message = '用户不存在(500)'
          const event = new CustomEvent('errorOccurred', {
            detail: error.message
          })
          window.dispatchEvent(event)
          break
        case 501:
          error.message = '服务未实现(501)'
          break
        case 502:
          error.message = '网络错误(502)'
          break
        case 503:
          error.message = '服务不可用(503)'
          break
        case 504:
          error.message = '网络超时(504)'
          break
        case 505:
          error.message = 'HTTP版本不受支持(505)'
          break
        default:
          error.message = '连接出错'
      }
    } else {
      error.message = '连接服务器失败!'
    }

    // eventBus.$emit("showErrorPopup", error.message);
    return Promise.reject(error)
  }
)

/**
 * 请求核心函数
 * @param {*} options
 * @returns 结果
 */
function request (options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
//   console.log(options.method)
  if (config.env === 'prod') {
    service.defaults.baseURL = config.baseApi
  } else {
    service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
  }
  console.log(config)
  console.log(config.baseApi)
  console.log(service.defaults.baseURL)
  return service(options)
}

;['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      ...options
    })
  }
})

export default request
